package com.agileai.pm.module.base.handler;

import java.util.Date;

import com.agileai.common.KeyGenerator;
import com.agileai.domain.DataParam;
import com.agileai.domain.DataRow;
import com.agileai.hotweb.controller.core.StandardEditHandler;
import com.agileai.hotweb.domain.FormSelectFactory;
import com.agileai.hotweb.domain.core.User;
import com.agileai.hotweb.renders.LocalRenderer;
import com.agileai.hotweb.renders.RedirectRenderer;
import com.agileai.hotweb.renders.ViewRenderer;
import com.agileai.pm.domain.Consts;
import com.agileai.pm.domain.Project;
import com.agileai.pm.module.base.service.ProjectTestManage;

public class ProjectTestManageEditHandler
        extends StandardEditHandler {
    public ProjectTestManageEditHandler() {
        super();
        this.listHandlerClass = ProjectTestManageListHandler.class;
        this.serviceId = buildServiceId(ProjectTestManage.class);
    }
    
    public ViewRenderer prepareDisplay(DataParam param) {
		String operaType = param.get(OperaType.KEY);
		if (isReqRecordOperaType(operaType)){
			DataRow record = getService().getRecord(param);
			this.setAttributes(record);	
			param.put("PT_NAME",record.stringValue("PT_NAME") );
			param.put("PT_STATE", record.stringValue("PT_STATE"));
		}else if("insert".equals(operaType)){
			DataRow record = new DataRow();
			User user = (User) this.getUser();
			record.put("PT_CREATE", user.getUserId());
			record.put("PT_CREATE_NAME", user.getUserName());
			record.put("PT_TIME", new Date());
			this.setAttributes(record);	
		}
		this.setAttributes(param);
		this.setOperaType(operaType);
		processPageAttributes(param);
		return new LocalRenderer(getPage());
	}
    
    public ViewRenderer doSaveAction(DataParam param){
		String operateType = param.get(OperaType.KEY);
		String testName = param.stringValue("PT_NAME");
		if (OperaType.CREATE.equals(operateType)){
			String testId = KeyGenerator.instance().genKey();
			getService().createRecord(param,testId);
			this.refreshSession(testId,testName);
		}
		else if (OperaType.UPDATE.equals(operateType)){
			getService().updateRecord(param);	
		}
		return new RedirectRenderer(getHandlerURL(listHandlerClass));
	}
    
    protected void refreshSession(String testId,String testName) {
    	Project project = (Project)this.getSessionAttribute(Consts.ProjectSessionKey);
    	project.setActiveTestId(testId);
    	project.setActiveTestName(testName);
    	this.getSessionAttributes().put(Consts.ProjectSessionKey, project);
	}

    protected void processPageAttributes(DataParam param) {
        setAttribute("PT_STATE",FormSelectFactory.create("TS_STATE").addSelectedValue(getOperaAttributeValue("PT_STATE","INITIALIZE")));
    }

    protected ProjectTestManage getService() {
        return (ProjectTestManage) this.lookupService(this.getServiceId());
    }
}
